<?php


namespace App\Models\CacheModel\zl1_relation;


use App\Models\CacheModel\Goods;
use App\Models\CacheModel\Recode;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use App\Models\Api\BaseCache;
use think\Exception;
use think\Log;
use AstroTool\Cache\CacheManage;

class Zl1RelationAnalysisFitYou extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl1_relation_analysis_fit_you';

    protected $cacheModel = 'relation_analysis.fit_you';


    /**
     * 添加 解锁 适合你的Ta
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function SaveData($order_id, $uid, $rid, $data)
    {
        try
        {
            $this->saveAll($data);
        }
        catch (\Exception $e)
        {
            Log::write($order_id . '添加 适合你的Ta 数据失败：' . $e->getMessage() . '[ ' . $e->getFile() . '：' . $e->getLine() . ' ]', 'error', true);
            return false;
        }
        $key = $uid . ':' . $rid;
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->rmCache();
        return true;
    }

    /**
     * 更新用户 适合你的Ta 数据
     * @param $uid
     * @param $rid
     * @param $data
     * @param $where
     * @return bool
     * @throws \Exception
     */
    public function UpdateData($uid, $rid, $data, $where)
    {
        try
        {
            $this->where($where)->update($data);
        }
        catch (\Exception $e)
        {
            Log::write(json_encode($where, true) . '更新 适合你的Ta 数据失败：' . $e->getMessage() . '[ ' . $e->getFile() . '：' . $e->getLine() . ' ]', 'error', true);
            return false;
        }
        $key = $uid . ':' . $rid;
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->rmCache();
        //删除档案解锁的 报告 订单编号缓存
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType($rid)->rmCache('list');
        return true;
    }

    /**
     * 适合你的Ta 入队加 数据写入
     * @param int $uid
     * @param int $rid
     * @param array $unlcok_gids 解锁商品
     * @param $order_id
     * @throws \Exception
     */
    public function SaveAndQueue($uid, $rid, $unlcok_gids, $order_id)
    {
        $now_time = time();
        $array = [];
        $recode = (new Recode())->getInfoById($rid);
        if ($recode)
        {
            $utilModel = new Util();
            $recode['sun'] = mb_substr($utilModel->recodeAstro($recode['sun']), 0, 2);
            $recode['moon'] = mb_substr($utilModel->recodeAstro($recode['moon']), 0, 2);
            $recode['asc'] = mb_substr($utilModel->recodeAstro($recode['asc']), 0, 2);
            unset($recode['status'], $recode['aid'], $recode['or_day'], $recode['merc'], $recode['venu'], $recode['mars'], $recode['jupi'], $recode['satu'], $recode['non'], $recode['lili'], $recode['juno'], $recode['mc'], $recode['is_read']);
        }
        $recodeStr = json_encode($recode, JSON_UNESCAPED_UNICODE);

        foreach ($unlcok_gids as $k => $v)
        {
            $array[] = [
                'uid' => $uid,
                'rid' => $rid,
                'gid' => $v,
                'order_num' => $order_id,
                'status' => 1,
                'recode_info' => $recodeStr,
                'create_time' => $now_time,
            ];
        }
        $this->SaveData($order_id, $uid, $rid, $array);
        if (Util::getVips($uid, 23, 0))
        {
            $queueDelay = 0;
        }
        //适合你的Ta 入队
        Util::queuePush('relation_analysis_fit_you', [
            'uid' => $uid,
            'recode' => $recode,
            'unlock_gids' => $unlcok_gids,
            'order_id' => $order_id,
            'push_switch' => true // 是否发送消息与推送
        ], $queueDelay ?? null);
    }

    /**
     * 获取档案解锁的 适合你的那个Ta 订单编号
     * @param int $uid
     * @param int $rid
     * @return array|mixed
     * @throws \Exception
     */
    public function getRecodeFitYouOrderIds(int $uid, int $rid)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setListKeyType($rid)->ZsGetIocData('list', function () use ($uid, $rid)
        {
            try
            {
                $orderIds = $this->where(['uid' => $uid, 'rid' => $rid])->group('order_num')->column('order_num', 'order_num');

                return array_flip_key_value($orderIds);
            }
            catch (Exception $e)
            {
                return [];
            }
        });
    }

    /**
     * 获取订单备份档案信息
     * @param string $order_id
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function getOrderRecodeBackRecode($order_id)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('details_back_recode', $order_id)->getDataAndSet(function () use ($order_id)
        {
            try
            {
                return $this
                    ->where(['order_num' => $order_id])
                    ->group('order_num')
                    ->column('recode_info', 'id');
            }
            catch (\Exception $e)
            {
                return [];
            }
        }, [], 'details_back_recode');
    }

    /**
     * 获取档案当前状态解锁 适合你的Ta
     * @param $uid
     * @param $rid
     * @return array
     * @throws \Exception
     */
    public function getUnlockGids($uid, $rid): array
    {
        $recodeModel = new \App\Models\Api\Recode();
        $recodeInfo = $recodeModel->getRecode(['uid' => $uid, 'id' => $rid]);
        $arr = [
            'msg' => '',
            'gids' => []
        ];
        $fitYouData = $this->getFitYouReport($recodeInfo);
        if (!$fitYouData)
        {
            return $arr;
        }
        $goods = (new Goods())->batchGetInfoByIds(array_keys($fitYouData));

        $gname = [];
        foreach ($fitYouData as $fitYouDatum)
        {
            if (!$fitYouDatum['recode_is_change'])
            {
                $gname[] = $goods[$fitYouDatum['gid']]['name'];
                $arr['gids'][] = $fitYouDatum['gid'];
            }
        }

        if ($gname)
        {
            $arr['msg'] = implode(',', $gname) . '已购买';
        }

        return $arr;
    }

    /**
     * 获取用户档案解锁 适合你的Ta 详情
     * @param array $recode
     * @param array $field
     * @return array
     * @throws \Exception
     */
    public function getFitYouReport($recode, $field = [])
    {
        $recodeUniqueKey = "{$recode['year']}:{$recode['month']}:{$recode['day']}:{$recode['hour']}:{$recode['minute']}:{$recode['timezone']}:{$recode['ew']}:{$recode['long_deg']}:{$recode['long_min']}:{$recode['ns']}:{$recode['lat_deg']}:{$recode['lat_min']}:{$recode['is_summer']}";

        $fitYouData = $this->getFitYouReportALL($recode['uid'], $recode['id'], $field);

        foreach ($fitYouData as $gid => $fitYouReportDatum)
        {
            if (isset($fitYouReportDatum[$recodeUniqueKey]))
            {
                $fitYouReportDatum[$recodeUniqueKey]['recode_is_change'] = false;
                $fitYouData[$gid] = $fitYouReportDatum[$recodeUniqueKey];
                continue;
            }

            $resData = [];
            foreach ($fitYouReportDatum as $fitYouDatumItem)
            {
                if (empty($resData))
                {
                    $resData = $fitYouDatumItem;
                } else
                {
                    if ($fitYouDatumItem['id'] > $resData['id'])
                    {
                        $resData = $fitYouDatumItem;
                    }
                }
            }

            $resData['recode_is_change'] = true;

            $fitYouData[$gid] = $resData;
        }

        return $fitYouData;
    }

    /**
     * 通过 订单查看历史
     * @param $uid
     * @param $rid
     * @param $orderId
     * @param array $field
     * @return array
     * @throws \Exception
     */
    public function getOrderFitYouReport($uid, $rid, $orderId, $field = [])
    {
        $fitYouReportData = $this->getFitYouReportALL($uid, $rid, $field);

        $resData = [];
        foreach ($fitYouReportData as $gid => $fitYouReportDataLists)
        {
            foreach ($fitYouReportDataLists as $fitYouReportDetailsItem)
            {
                $fitYouReportDetailsItem['recode_is_change'] = false;   // 通过订单查看历史 默认档案未更新

                if ($fitYouReportDetailsItem['order_num'] === $orderId)
                {
                    $resData[$gid] = $fitYouReportDetailsItem;
                    break;
                }

                if (!isset($resData[$gid]))
                {
                    $resData[$gid] = $fitYouReportDetailsItem;
                } else
                {
                    if ($fitYouReportDetailsItem['id'] > $resData[$gid]['id'])
                    {
                        $resData[$gid] = $fitYouReportDetailsItem;
                    }
                }
            }
        }

        return $resData;
    }

    /**
     * 获取用户档案解锁 适合你的Ta 详情
     * @param $uid
     * @param $rid
     * @param array $field
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getFitYouReportALL($uid, $rid, $field = [])
    {
        $key = $uid . ':' . $rid;

        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $key)->getDataAndSet(function () use ($uid, $rid)
        {
            return $this->getFitYouReportByDb($uid, $rid);
        }, $field);

        if ($data && $field && is_string($data))
        {
            $data = [current($field) => json_decode($data, true)];
        } else
        {
            foreach ($data as $gid => $valueStr)
            {
                $data[$gid] = json_decode($valueStr, true);
            }
        }

        return $data;
    }

    /**
     * 通过数据库 获取用户 档案 计算的所有 适合你的Ta
     * @param $uid
     * @param $rid
     * @return array
     */
    protected function getFitYouReportByDb($uid, $rid): array
    {
        try
        {
            $data = $this->where(['uid' => $uid, 'rid' => $rid, 'status' => ['in', [1, 2, 3]]])->order('id asc')->column('gid,order_num,content,status,recode_info', 'id');

            $resData = [];
            foreach ($data as $key => $value)
            {
                $recode = json_decode($value['recode_info'], true);

                $recodeUniqueKey = "{$recode['year']}:{$recode['month']}:{$recode['day']}:{$recode['hour']}:{$recode['minute']}:{$recode['timezone']}:{$recode['ew']}:{$recode['long_deg']}:{$recode['long_min']}:{$recode['ns']}:{$recode['lat_deg']}:{$recode['lat_min']}:{$recode['is_summer']}";

                $value['name'] = $recode['name'] ?? '';
                $value['content'] = json_decode($value['content'], true);

                $resData[$value['gid']][$recodeUniqueKey] = $value;
            }

            foreach ($resData as $gid => $resDatum)
            {
                $resData[$gid] = json_encode($resDatum, JSON_UNESCAPED_UNICODE);
            }
        }
        catch (Exception $e)
        {
            $resData = [];
        }

        return $resData;
    }
}
